import React from 'react';
import ReactDOM from 'react-dom';
import {  ListView, Icon } from 'antd-mobile';
import SingleItem from '../../components/singleItem';

import { postRequest, getRequest } from '../../../tools/requests';

import './index.css';

const NUM_ROWS = 4;
let pageIndex = 1;

function genData(pIndex = 1) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
  }
  return dataBlob;
}

export default class CustomListView extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      goodsLists: [],
      dataSource,
      isLoading: true,
    };
  }
  componentDidMount() {
    this.rData = genData();
    this.setState({
      dataSource: this.state.dataSource.cloneWithRows(this.rData),
      isLoading: false,
      goodsLists: this.props.goodsLists,
    });
  }

  async onEndReached(event) {
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    this.setState({ isLoading: true });
    let pageAdd = ++pageIndex;
    const result = await postRequest('goods_list/', {page: pageAdd, page_size: 4});
    if (result.success) {
      this.rData = { ...this.rData, ...genData(pageAdd) };
      this.setState({
        goodsLists: result.data,
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
    }
  }

  render() {
    let index = this.state.goodsLists.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = this.state.goodsLists.length - 1;
      }
      const objImg = this.state.goodsLists[index--];
      return (
        <SingleItem key={rowID} item={objImg}></SingleItem>
      );
    };
    return (
      <div className="app-block">
        <ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderFooter={() => (<div style={{ padding: '15px', textAlign: 'center' }}>
            {this.state.isLoading ? <Icon type="loading" /> : ''}
          </div>)}
          renderRow={row}
          // renderBodyComponent={() => this.props.renderListViewBody()}
          className="am-list"
          pageSize={4}
          useBodyScroll
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached.bind(this)}
          onEndReachedThreshold={10}
          style={{marginTop: '121px'}}
        />
      </div>
    )
  }
}